<script>
import { Search, ArrowRight, ArrowLeft } from "@element-plus/icons-vue";
import { StudioAPI } from "../apis";
import { ElMessage } from "element-plus";
import DraggableUpload from "../components/DraggableUpload.vue";

import { ref } from "vue";
export default {
  setup() {
    const mediaRef = ref(null);
    return {
      mediaRef,
    };
  },

  data() {
    return {
      uploadFun: StudioAPI.draggableUpload,
      query: {
        page: 1,
        keywords: null,
        with_info: 1,
        page_size: 20,
      },
      showcases: [],
      products: [],
      has_more: false,
      media_types: ["IMAGE", "VIDEO"],
      editing_showcase: {
        showcase_id: null,
        media_urls: null,
        media_type: "IMAGE",
        description: null,
        product_id: null,
      },
    };
  },
  components: {
    DraggableUpload,
    Search,
    ArrowRight,
    ArrowLeft,
  },
  async mounted() {
    await this.getShowcases();
    await this.getProducts();
  },
  methods: {
    async getProducts() {
      const products = await StudioAPI.getProducts({});
      this.products = products;
    },

    async getShowcases() {
      const showcases = await StudioAPI.getShowcases(this.query);
      this.showcases = showcases;
      this.has_more = showcases.length === this.query.page_size;
    },
    async deleteShowcase(showcase_id) {
      const showcase_index = this.showcases.findIndex(
        (showcase) => showcase.showcase_id === showcase_id
      );
      if (showcase_index < 0) return;

      await StudioAPI.deleteShowcase({ showcase_id });
      this.showcases.splice(showcase_index, 1);
    },

    async nextPage() {
      this.query.page += 1;
      await this.getShowcases();
    },
    async prevPage() {
      this.query.page -= 1;
      await this.getShowcases();
    },
    async searchShowcases() {
      this.query.page = 1;
      await this.getShowcases(this.query);
    },
    async confirmKeywords(page) {
      this.query.page = isNaN(page) ? 1 : page;
      await this.getShowcases();
    },

    // 点击顾客行
    async clickShowcaseRow(showcase) {
      const index = this.showcases.findIndex(
        (c) => c.showcase_id === showcase.showcase_id
      );
      if (index < 0) return;
      console.log(showcase);
      this.editing_showcase = Object.assign({}, showcase);

      this.mediaRef.images = this.editing_showcase.media_urls.map((url) => {
        return {
          url,
        };
      });
    },

    async addShowcase() {
      this.reset();
    },

    async confirmUpsert() {
      this.editing_showcase.media_urls = this.mediaRef.images.map(
        (i) => i.response || i.url
      );

      if (this.editing_showcase.showcase_id) {
        const {
          success,
          data: showcase,
          message,
        } = await StudioAPI.updateShowcase({
          ...this.editing_showcase,
        });

        if (!success) {
          ElMessage.warning(message);
          return;
        }

        // 出错
        if (!showcase.showcase_id) throw showcase;

        const index = this.showcases.findIndex(
          (p) => p.showcase_id === showcase.showcase_id
        );
        if (index > -1) {
          const updated_showcase = await StudioAPI.getShowcase({
            showcase_id: showcase.showcase_id,
          });
          this.showcases[index] = updated_showcase;
        }
      } else {
        const {
          success,
          data: showcase,
          message,
        } = await StudioAPI.createShowcase({
          ...this.editing_showcase,
        });
        if (!success) {
          ElMessage.warning(message);
          return;
        }

        // 出错
        if (!showcase.showcase_id) throw showcase;
        const updated_showcase = await StudioAPI.getShowcase({
          showcase_id: showcase.showcase_id,
        });
        this.showcases.splice(0, 0, updated_showcase);
      }
      this.reset();
    },
    reset() {
      this.editing_showcase = {
        showcase_id: null,
        media_urls: [],
        media_type: "IMAGE",
        description: null,
        // name: null,
        // product_id: null,
      };
      this.mediaRef.images = [];
    },
  },
};
</script>
<template>
  <el-container>
    <el-main style="padding: 5px" width="auto">
      <div class="filter-header">
        <!-- 底部换页 -->
        <div style="display: flex">
          <el-input
            v-model="query.keywords"
            clearable
            placeholder="备注"
            size="large"
            @keyup.enter="confirmKeywords"
          >
            <template #prefix>
              <el-icon class="el-input__icon"><search /></el-icon>
            </template>
          </el-input>
          <div style="flex: 1; margin-left: 20px">
            <el-button
              @click="prevPage"
              :disabled="query.page === 1"
              size="large"
              style="width: 100%"
            >
              <el-icon size="20"><arrow-left /></el-icon>
            </el-button>
          </div>
          <div style="flex: 1; margin-left: 5px">
            <el-button
              @click="nextPage"
              :disabled="!has_more"
              size="large"
              style="width: 100%"
            >
              <el-icon size="20"><arrow-right /></el-icon>
            </el-button>
          </div>
        </div>
        <div>
          <el-button @click="addShowcase" size="large" style="width: 100%">
            添加案例
          </el-button>
        </div>
      </div>
      <el-table
        :data="showcases"
        highlight-current-row
        height="88vh"
        @row-click="clickShowcaseRow"
        stripe
      >
        <el-table-column label="关联产品" width="140">
          <template #default="scope">
            <el-tag
              size="large"
              style="margin-right: 10px"
              disable-transitions
              >{{ scope.row.product.name }}</el-tag
            >
          </template>
        </el-table-column>

        <el-table-column label="类别" width="140">
          <template #default="scope">
            <el-tag size="large" disable-transitions>{{
              scope.row.media_type
            }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="name" label="备注" width="200" />
        <el-table-column label="图片">
          <template #default="scope">
            <el-image
              v-for="(media_url, index) of scope.row.media_urls"
              :key="media_url"
              style="
                width: 40px;
                height: 40px;
                display: inline-block;
                margin-right: 10px;
              "
              :src="media_url"
              fit="cover"
              :preview-src-list="scope.row.media_urls"
              :initial-index="index"
              :preview-teleported="true"
            />
          </template>
        </el-table-column>
        <el-table-column label="删除" width="140">
          <template #default="scope">
            <el-button
              type="danger"
              @click="deleteShowcase(scope.row.showcase_id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <!-- 右侧表单 -->
    <el-aside style="padding: 5px; width: 400px">
      <el-card shadow="hover">
        <template #header>
          <div class="flex-between">
            <div style="font-size: var(--el-font-size-large)">增改销售</div>
            <div>
              <el-button type="primary" @click="confirmUpsert" size="large">
                保存
              </el-button>
            </div>
          </div>
        </template>
        <el-form :model="editing_showcase" label-width="80px">
          <el-form-item label="类型" prop="media_type">
            <el-radio-group
              v-model="editing_showcase.media_type"
              :disabled="editing_showcase.showcase_id !== null"
            >
              <el-radio
                v-for="media_type in media_types"
                :key="media_type"
                :label="media_type"
                size="large"
                border
              >
                {{ media_type }}
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="预览图" prop="media_urls">
            <draggable-upload
              ref="mediaRef"
              :upload-fun="uploadFun"
              :multiple="true"
              :limit="20"
            ></draggable-upload>
          </el-form-item>
          <el-form-item label="关联 产品" prop="product_ids">
            <el-radio-group v-model="editing_showcase.product_id">
              <el-radio
                v-for="product in products"
                :key="product.product_id"
                :label="product.product_id"
                size="large"
                border
              >
                {{ product.name + "（" + product.category_name + "）" }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注" prop="name">
            <el-input v-model="editing_showcase.name" />
          </el-form-item>
        </el-form>
      </el-card>
    </el-aside>
  </el-container>
</template>

<style scoped>
.image-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, 200px);
  row-gap: 10px;
  column-gap: 10px;
  grid-auto-rows: 240px;
  overflow: auto;
  height: calc(100vh - 70px);
}

.image-item {
  position: relative;
  width: 200px;
  height: 200px;
  border-radius: 5px;
}

.el-table .el-table__cell {
  position: unset;
}
</style>
